<template>
  <div class="app-container">
    <div style="margin-bottom: 10px;" />
    <el-row type="flex" justify="center" align="middle">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header">
            <div class="title-box" style="padding-top: 10px; padding-bottom: 13px;">
              <span>组织管理</span>
            </div>
          </div>
          <el-input v-model="filterOrgText" v-perm="['orgnization-search']" class="mgb-15" :placeholder="filterPlaceholderText" />
          <div style="margin-bottom: 10px;" />
          <el-tree
            ref="OrganizeTreeRef"
            v-loading="viewLoading"
            :filter-node-method="filterNode"
            :data="OrganizeTree"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <span v-if="data.type==OrgnizeType.ANCESTOR" class="mgl-10"><span class="tenant-title">{{ data.name }}</span><el-tag class="mgl-10" type="info" size="mini">集团</el-tag></span>
                <span v-else-if="data.type==OrgnizeType.AREA" class="mgl-10"><span class="tenant-title">{{ data.name }}</span><el-tag class="mgl-10" type="info" size="mini">区域</el-tag></span>
                <span v-else-if="data.type==OrgnizeType.FACTORY" class="mgl-10"><span class="company-title">{{ data.name }}</span><span v-if="data.sub_title">({{ data.sub_title }})</span><el-tag class="mgl-10" type="info" size="mini">公司</el-tag></span>
                <span v-else-if="data.type==OrgnizeType.DEPARTMENT" class="mgl-10"><span class="department-title">{{ data.name }}</span><el-tag class="mgl-10" type="info" size="mini">部门</el-tag></span>
              </span>
              <span>
                <el-button v-if="data.type!=OrgnizeType.DEPARTENT" type="text" size="mini" icon="el-icon-plus" @click="handleAddButton(data)" />
                <el-button v-if="data.type!=OrgnizeType.ANCESTOR" type="text" size="mini" icon="el-icon-edit" @click="handleUpdateButton(data)" />
                <el-button v-if="data.type!=OrgnizeType.ANCESTOR" type="text" size="mini" icon="el-icon-delete" @click="handleDeleleButton(data)" />
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
    </el-row>
    <!--弹窗：新增或编辑权限-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="temp" label-position="top" :rules="rules">
        <el-form-item v-if="dialogStatus=='updateButton'" label="ID">
          <el-input v-model="temp.id" disabled />
        </el-form-item>
        <el-form-item v-if="temp.type===OrgnizeType.FACTORY">
          <el-radio-group v-model="company_type">
            <el-radio :label="2">电厂</el-radio>
            <el-radio :label="1">餐厨</el-radio>
            <el-radio :label="3">清/转运</el-radio>
          </el-radio-group>
<!--          <el-switch v-model="is_food" active-text="餐厨" inactive-text="电厂"></el-switch>-->
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item v-if="temp.type===OrgnizeType.FACTORY" label="副标题">
          <el-input v-model="temp.sub_title" />
        </el-form-item>
        <el-form-item label="父级节点">
          <el-input v-model="temp.parent_name" :disabled="true" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="temp.type" placeholder="请选择类型" @change="organizeTypeChange">
            <el-option v-for="(item, index) in typesArr" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input v-model="temp.sort" type="number" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" type="textarea" placeholder="请输入描述或备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='addButton'" type="primary" @click="addButton" v-loading="controlLoading">确定</el-button>
        <el-button v-if="dialogStatus=='updateButton'" type="primary" @click="updateButton" v-loading="controlLoading">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import orgnizeApi from '@/api/orgnization'
import { root, confirm, tenantType,OrgnizeType, buttonType } from '@/utils/constants'
import { parseTime, resetTemp } from '@/utils'
import debounce from 'lodash/debounce'

export default {

  name: 'OrganizeManage',
  data() {
    return {
      rules: {
        name: [{ required: true, message: '必填', trigger: 'blur' }],
        sort: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      viewLoading: false,
      controlLoading:false,
      tableQuery: {
        nick: null
      },
      tenantType,
      buttonType,
      OrgnizeType,
      filterPlaceholderText: '输入名称过滤',
      filterOrgText: '',
      OrganizeTree: [],
      treeProps: {
        label: 'label',
        children: 'children'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        idx: null,
        id: null,
        name: null,
        sub_title: null,
        title: null,
        description: null,
        parent_id: null,
        parent_name: null,
        is_food:null,
        parent: null,
        type: null,
        sort: null
      },
      company_type:2,
      typesArr:[],
      textMap: {
        addButton: '添加部门',
        updateButton: '更新部门',
        deleteButton: '删除部门'
      }
    }
  },

  created() {
    this.fetchData()
  },

  watch: {
    'filterOrgText': debounce(function(val) {
      this.$refs.OrganizeTreeRef.filter(val)
    }, 600)
  },

  methods: {
    // 查询
    fetchData() {
      this.viewLoading = true
      const params = {is_manage:1}
      orgnizeApi.orgnizeTree(params).then(res => {
        this.OrganizeTree = res.data
        this.viewLoading = false
      }).catch(err => {
        this.OrganizeTree = []
        this.viewLoading = false
      })
      this.typesArr=[
        {
          label:'区域',
          value:'area',
          disabled:false
        },
        {
          label:'公司',
          value:'factory',
          disabled:false
        },
        {
          label:'部门',
          value:'department',
          disabled:false
        }
      ]
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    organizeTypeChange(val){
      if (val=='factory'){
        if (!this.company_type)
          this.company_type=2
      }else {
        if (this.company_type>0)
          this.company_type=0
      }
    },
    handleAddButton(data) {
      this.dialogStatus = 'addButton'
      resetTemp(this.temp)
      this.temp.parent = data
      this.temp.parent_name = data.name
      this.temp.parent_id = data.id
      this.company_type=2
      this.temp.type = this.orgButtonType(buttonType.ADD, data.type)
      this.textMap[this.dialogStatus] = this.dialogTitle(buttonType.ADD, data.type)
      this.temp.sort = 10
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
    },
    addButton() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        this.temp.is_food=0
        if (this.temp.type===OrgnizeType.FACTORY){
          this.temp.is_food = this.company_type
        }
        const data = Object.assign({}, this.temp)// copy obj
        this.controlLoading=true
        orgnizeApi.orgnizeStore(data).then((res) => {
          this.dialogFormVisible = false
          this.controlLoading=false
          if (res.code === -1) {
            return
          }
          this.fetchData()
          this.$message.success('添加成功')
        })
      })
    },
    findOrganize(childs, pid) {
      if (!childs.length) { return null }
      for (const org of childs) {
        if (org.id === pid) { return org }
        if (org.children) {
          const corg = this.findOrganize(org.children, pid)
          if (corg) { return corg }
        }
      }
      return this.OrganizeTree[0]
    },

    /**
       * 更新按钮权限
       */
    handleUpdateButton(data) {
      this.dialogStatus = 'updateButton'
      this.temp = Object.assign({}, data) // copy obj
      const parent = this.findOrganize(this.OrganizeTree[0].children, this.temp.parent_id)
      this.temp.parent = parent
      this.temp.parent_name = parent.name
      this.temp.type = this.orgButtonType(buttonType.UPDATE, data.type)
      this.company_type = this.temp.is_food
      this.textMap[this.dialogStatus] = this.dialogTitle(buttonType.UPDATE, data.type)
      this.dialogFormVisible = true
      this.$nextTick(() => this.$refs['dataForm'].clearValidate())
    },
    updateButton() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        if (this.temp.type===OrgnizeType.FACTORY){
          this.temp.is_food = this.company_type
        }
        const data = Object.assign({}, this.temp)// copy obj
        this.controlLoading=true
        orgnizeApi.orgnizeStore(data).then(res => {
          this.dialogFormVisible = false
          this.controlLoading=false
          this.fetchData()
          this.$message.success('更新成功')
        })
      })
    },

    /**
       * 删除按钮权限
       */
    handleDeleleButton(data) {
      this.dialogStatus = 'deleteButton'
      this.$confirm(`您确定要永久删除该选项？`, '提示', confirm).then(() => {
        orgnizeApi.orgnizeDelete(data.id).then(() => {
          this.fetchData()
          this.$message.success(`删除成功`)
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    orgButtonType(typeName, type) {
      if (typeName === buttonType.ADD) {
        this.typesArr.forEach(tp=>tp.disabled=false)
        if (type === OrgnizeType.FACTORY) {
          this.typesArr[0].disabled=true
          this.typesArr[1].disabled=true
          return OrgnizeType.DEPARTMENT
        }
        this.typesArr[2].disabled=true
        return OrgnizeType.AREA
      } else {
        this.typesArr.forEach(tp=>tp.disabled=true)
        if (type === OrgnizeType.FACTORY) {
          this.typesArr[2].disabled=false
        } else if (type === OrgnizeType.AREA){
          this.typesArr[0].disabled=false
          this.typesArr[1].disabled=false
        }
        return type
      }
    },
    dialogTitle(typeName, type) {
      if (typeName === buttonType.ADD) {
        return '新增'
      }
      return '更新'
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import 'src/styles/variables.scss';
  .mgl-10 {
      margin-left: 10px;
    }
  .tenant-title{
    font-weight: normal;
    color:$tenant-color;
  }
  .company-title{
    font-weight: lighter;
    color: $company-color;
    font-size: small;
    margin-right: 10px;
  }
  .department-title{
    font-weight: lighter;
    color: $department-color;
    font-size: small;
  }
  .title-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      font-size: 22px;
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .mgb-15 {
    margin-bottom: 15px;
  }
</style>
